﻿using Microsoft.Extensions.Hosting;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SBlogCore.MqttService.Extenions
{
    public class MqttHostService : IHostedService, IDisposable
    {
        private readonly MqttServer _server;
        private readonly IMqttServerEvents _events;

        public MqttHostService(MqttServer server, IMqttServerEvents events)
        {
            _server = server;
            _events = events;
        }
        public void Dispose()
        {

        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _server.ClientConnectedAsync += _events.ClientConnectedAsync; //客户端连接事件
            _server.ClientDisconnectedAsync += _events.ClientDisconnectedAsync; // 客户端关闭事件
            _server.ApplicationMessageNotConsumedAsync += _events.ApplicationMessageNotConsumedAsync; // 消息接收事件
            _server.ClientSubscribedTopicAsync += _events.ClientSubscribedTopicAsync; // 客户端订阅主题事件
            _server.ClientUnsubscribedTopicAsync += _events.ClientUnsubscribedTopicAsync; // 客户端取消订阅事件
            _server.StartedAsync += _events.StartedAsync; // 启动后事件
            _server.StoppedAsync += _events.StoppedAsync; // 关闭后事件
            _server.InterceptingPublishAsync += _events.InterceptingPublishAsync; // 消息接收事件
            _server.ValidatingConnectionAsync += _events.ValidatingConnectionAsync; // 用户名和密码验证有关
            _server.StartAsync();
            return Task.CompletedTask;
        }



        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
